import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_member/stytle/SvgImg.dart';
import 'package:flutter_member/utils/color.dart';
import 'package:flutter_member/widget/button_icon.dart';
import 'package:flutter_member/widget/custom_appbar.dart';
import 'package:flutter_member/widget/loading_dialog.dart';
import 'package:flutter_member/widget/no_data.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:flutter_svg/svg.dart';
import 'package:fsearch/fsearch.dart';
import 'package:parse_server_sdk/parse_server_sdk.dart';
import 'package:collection/collection.dart';
import 'album_info.dart';
/*
 * 相册页面
 * 瀑布流布局
 */
class StudentPhotoAlbumPage extends StatefulWidget {
  @override
  _StudentPhotoAlbumPageState createState() => _StudentPhotoAlbumPageState();
}

class _StudentPhotoAlbumPageState extends State<StudentPhotoAlbumPage> {
//  第一次存储 相册数据
  List<dynamic> _listAlbum = [];

//  将相册数据转化为map
  Map mapAlbum = {};

//  以相册名保存
  List<dynamic> _listAlbumName = [];

//  转化map
  Map mapAlbumName = {};

//  顯示大圖
  String bigPicture = '';

  ///  判断输入框右侧按钮点击事件，
  ///  如果是ture则使用瀑布流方式布局
  ///  否则使用一大图两小图的格式
  bool isVertical = true;

  /// 显示相册详情
  bool albumInfo = false;

  /// 相册详情图片数据集合
  List<dynamic> listAlbumInfo = [];

  // 加载中
  bool _loading = true;

  // 搜索狀態
  bool searchType = false;

  @override
  void initState() {
    super.initState();
//    _getAlbum();
    _getByDate();
  }

  bool searching4 = false;

  /// 通过日期查询
  Future<void> _getByDate({bool isLoading = true}) async {
    if (isLoading == true) {
      setState(() => _loading = true);
    }
    _listAlbum.clear();
    final ParseUser user = await ParseUser.currentUser() as ParseUser;
    var member = await ParseObject("Member")
        .getObject(user.get('member').get('objectId'));
    var queryAlum = QueryBuilder<ParseObject>(ParseObject('Album'))
      ..whereRelatedTo(
          'albums', 'Student', member.result['student']['objectId']);
    ParseResponse rep = await queryAlum.query();

    if (rep.results != null && rep.success) {
      rep.results.map((e) => print(e)).toList();
      rep.results.map((e) async {
        var querPhoto = QueryBuilder<ParseObject>(ParseObject("Photo"))
          ..whereRelatedTo("images", "Album", "0AHyFzV30T");
        var repPhoto = await querPhoto.query();
        if (repPhoto.success && repPhoto.results != null) {
          repPhoto.results.map((photo) {
            setState(() {
              _loading = false;
              _listAlbum.add({
                'name': e['displayName'],
                'date': formatDate(photo['createdAt'], [yyyy, '-', mm]),
                'url': photo['src']['url']
              });
              mapAlbum = groupBy(_listAlbum, (obj) => obj['date']);
            });
          }).toList();
        }
        mapAlbumName = groupBy(_listAlbum, (obj) => obj['name']);
      }).toList();
    }
    setState(() => _loading = false);
  }

  @override
  Widget build(BuildContext context) {
    return CustomAppBar(
        title: '学生相册',
        upperColor: 0xff2D7FC7,
        lowerColor: 0xffE5EEF6,
        hight: 75,
        body: WillPopScope(
          child: Column(
            children: [_searchWidget(), _body()],
          ),
          onWillPop: () {
            setState(() {
              albumInfo = false;
              if (isVertical == true) {
                Navigator.pop(context);
              }
            });
            return null;
          },
        ));
  }

  Widget _body() {
    if (_loading == true) {
      return CLoadingDialog(
        text: "加載中",
      );
    } else if (searchType == true) {

    } else if (_listAlbum.length == 0) {
      return NoDataWidget();
    } else {
      return _AlbumBodyWidget();
    }
  }

//  按照相冊名稱顯示
  Widget _AlbumBodyWidget() {
    return Column(
      children: [
        isVertical == true
            ? Expanded(
            child: EasyRefresh(
              header: PhoenixHeader(),
              footer: PhoenixFooter(),
              onRefresh: () => _getByDate(isLoading: false),
              child: SingleChildScrollView(
                child: Column(
                  children: _listAlbumWidget(),
                ),
              ),
            ))
            : Expanded(
          child: EasyRefresh(
            onRefresh: () => _getByDate(isLoading: false),
            header: PhoenixHeader(),
            footer: PhoenixFooter(),
            child: SingleChildScrollView(
              child: Column(
                children: _listCustomAlbum(),
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget _dateOfName() {}

//  搜索输入框组件
  Widget _searchWidget() {
    return Container(
      width: ScreenUtil().setWidth(323),
      height: ScreenUtil().setHeight(38),
      padding: EdgeInsets.only(top: 5, bottom: 5),
      margin: EdgeInsets.only(top: 15),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Expanded(
            child: FSearch(
              backgroundColor: mainBackgroundColor,
              hints: [
                "搜尋相關日期",
                "搜尋相片日期",
              ],
              corner: FSearchCorner(
                  leftTopCorner: 35.0,
                  leftBottomCorner: 35.0,
                  rightBottomCorner: 35.0,
                  rightTopCorner: 35.0),
              strokeWidth: 1.0,
              shadowColor: Colors.black12,
              shadowBlur: 5.0,
              shadowOffset: Offset(2.0, 2.0),
              style: TextStyle(
                  fontSize: 16.0, height: 1.0, color: Colors.tealAccent),
              margin: EdgeInsets.only(left: 12.0, right: 12.0),
              padding:
              EdgeInsets.only(left: 6.0, right: 6.0, top: 3.0, bottom: 3.0),
              prefixes: [
                Container(
                  width: 10.0,
                )
              ],
              suffixes: [
                Icon(
                  Icons.search,
                  size: ScreenUtil().setWidth(20),
                  color: Color(0xff2d7fc7),
                ),
                const SizedBox(width: 6.0),
              ],
              onSearch: (value) {
                setState(() {
                  searching4 = true;
                });
              },
            ),
          ),
          SizedBox(
            width: 15,
          ),
          IconButton(
            icon: ImageIcon(
              AssetImage(
                  isVertical ? "images/album_v.png" : "images/album_h.png"),
              color: Color(0xff93BB24),
              size: 22,
            ),
            onPressed: () {
//              _getByName();
              setState(() {
                isVertical = !isVertical;
              });
            },
          )
        ],
      ),
    );
  }

  List<Widget> _listAlbumWidget() {
    List<Widget> listWidget = [];
    mapAlbum.forEach((key, value) {
      listWidget.add(
        Container(
          padding: EdgeInsets.all(20),
          height: ScreenUtil().setHeight(465),
          child: AlbumWidget(year: key.toString(), list: value),
        ),
      );
    });
    return listWidget;
  }

//  默認顯示的瀑布流照片佈局
  Widget AlbumWidget({String year, List list}) {
    return Expanded(
//      margin: EdgeInsets.only(left: 15, right: 15, top: 10),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            year,
            textAlign: TextAlign.left,
            style: TextStyle(
                color: Color(0xff69BF97),
                fontSize: ScreenUtil().setSp(15),
                fontWeight: FontWeight.w400),
          ),
          Expanded(
            child: Container(
              margin: EdgeInsets.only(top: 10),
              child: new StaggeredGridView.countBuilder(
                crossAxisCount: 4,
                itemCount: list.length,
                physics: new NeverScrollableScrollPhysics(),
                itemBuilder: (BuildContext context, int index) => new Container(
                  decoration: BoxDecoration(
                      color: Colors.green,
                      borderRadius: BorderRadius.all(Radius.circular(8))),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(8),
                    child: Image.network(
                      list[index]['url'],
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
                staggeredTileBuilder: (int index) => StaggeredTile.fit(2),
                mainAxisSpacing: 15.0,
                crossAxisSpacing: 15.0,
              ),
            ),
          )
        ],
      ),
    );
  }

  List<Widget> _listCustomAlbum() {
    List<Widget> listWidget = [];
    mapAlbumName.forEach((key, value) {
      listWidget.add(
        AlbumTitle(
            title: key,
            count: value.length,
            info: value[0]['date'],
            picList: value),
      );
      listWidget.add(CustomAlbum(list: value));
    });
    return listWidget;
  }

  /// 含有标题的相册
  /// 左边一张大图，右边两张小图
  Widget CustomAlbum({@required List list}) {
    return Container(
      child: Column(
        children: [
          Container(
            width: ScreenUtil().setWidth(335),
            height: ScreenUtil().setHeight(265),
            margin: EdgeInsets.only(top: 10, bottom: 10),
            child: listAlbumWidget(list: list),
          ),
        ],
      ),
    );
  }

//  按照名称分类相册
  Widget listAlbumWidget({@required List list}) {
    switch (list.length) {
      case 0:
        Container(
            width: ScreenUtil().setWidth(335),
            height: ScreenUtil().setHeight(265),
            margin: EdgeInsets.only(right: 2),
            decoration: BoxDecoration(
                borderRadius: BorderRadius.only(
                    bottomLeft: Radius.circular(8),
                    topLeft: Radius.circular(8)),
                image: DecorationImage(
                    image: NetworkImage(list[0]['url']), fit: BoxFit.fill)));
        break;
      case 1:
        return Row(
          children: [
            Expanded(
              flex: 1,
              child: Container(
                  margin: EdgeInsets.only(right: 2),
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.only(
                          bottomLeft: Radius.circular(8),
                          topLeft: Radius.circular(8)),
                      image: DecorationImage(
                          image: NetworkImage(list[0]['url']),
                          fit: BoxFit.fill))),
            ),
          ],
        );
        break;
      default:
        return Container(
          width: ScreenUtil().setWidth(335),
          height: ScreenUtil().setHeight(265),
          margin: EdgeInsets.only(top: 10, bottom: 10),
          child: Row(
            children: [
              Container(
                  width: ScreenUtil().setWidth(230),
                  height: ScreenUtil().setHeight(265),
                  margin: EdgeInsets.only(right: 2),
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.only(
                          bottomLeft: Radius.circular(8),
                          topLeft: Radius.circular(8)),
                      image: DecorationImage(
                          image: NetworkImage(list[0]['url']),
                          fit: BoxFit.fill))),
              Column(
                children: [
                  Container(
                    decoration: BoxDecoration(
                        borderRadius:
                        BorderRadius.only(topRight: Radius.circular(8)),
                        color: Colors.teal,
                        image: DecorationImage(
                            image: NetworkImage(list[1]['url']),
                            fit: BoxFit.fill)),
                    width: ScreenUtil().setWidth(100),
                    height: ScreenUtil().setHeight(132),
                  ),
                  SizedBox(
                    height: 2,
                  ),
                  Container(
                    decoration: BoxDecoration(
                        borderRadius:
                        BorderRadius.only(bottomRight: Radius.circular(8)),
                        color: Colors.tealAccent,
                        image: DecorationImage(
                            image: NetworkImage(list[2]['url']),
                            fit: BoxFit.fill)),
                    width: ScreenUtil().setWidth(100),
                    height: ScreenUtil().setHeight(116),
                  ),
                ],
              )
            ],
          ),
        );
        break;
    }
  }

//  相册标题
  Widget AlbumTitle({String title, num count, String info, List picList}) {
    return Container(
      margin: EdgeInsets.only(left: 30, right: 15, top: 10),
      child: Column(
//        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            title,
            textAlign: TextAlign.left,
            style: TextStyle(
                color: Color(0xff69BF97),
                fontWeight: FontWeight.w500,
                fontSize: ScreenUtil().setSp(15)),
          ),
          SizedBox(
            height: 5,
          ),
          Row(
            children: <Widget>[
              Expanded(
                child: RichText(
                  text: TextSpan(
                      text: '共${count}張照片',
                      style: TextStyle(color: Color(0xff7897B2)),
                      children: <TextSpan>[
                        TextSpan(
                          text: '\t\t\t\t於${info}上傳',
                          style: TextStyle(color: Color(0xff7897B2)),
                        )
                      ]),
                ),
              ),
              ButtonIcon(
                  title: '更多',
                  onPressed: () {
                    Navigator.push(context,
                        MaterialPageRoute(builder: (context) {
                          return AlbumInfo(
                            listAlbumInfo: picList,
                          );
                        }));
                  })
            ],
          ),
          SizedBox(
            height: 5,
          ),
        ],
      ),
    );
  }
  /// 搜索結果為空
  Widget _noSeachWidget() {
    return Container(
      height: ScreenUtil().setHeight(667),
      child: Center(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            SvgPicture.string(SvgImg.svgAlbumImg),
            Row(
              children: [
                Icon(
                  Icons.search,
                  color: Color(0xff9B9B9B),
                ),
                Text(
                  '暫沒有任何搜尋結果',
                  style: TextStyle(
                      color: Color(0xff9B9B9B),
                      fontSize: ScreenUtil().setSp(14)),
                ),
              ],
            )
          ],
        ),
      ),
    );
  }
}

